<template lang="pug">
.cp-train-cs-popup
  el-dialog.tcs-pop(
    :title="title",
    :visible="visible",
    @close="closeDialog",
    :close-on-click-modal="!isEdit",
    width="60%")
    el-form.tcs-pop-form(:model="formData", :inline="false", :rules="rules", ref="formData", label-width="80px")
      el-row(:gutter="24")
        el-col(:span="12")
          el-form-item(label="名称", prop="name")
            el-input(v-model="formData.name", :disabled="!isEdit")
        el-col(:span="12")
          el-form-item(label="编码", prop="code")
            el-tooltip(placement="top", :content="formData.code", :disabled="!formData.code")
              el-input(v-model="formData.code", placeholder="自动生成", disabled)
      el-row(:gutter="24")
        el-col(:span="12")
          el-form-item(label="描述", prop="desc")
            el-input(type="textarea", :rows="3", :disabled="!isEdit", placeholder="请输入内容", v-model="formData.desc")
        el-col(:span="12")
          div
            el-form-item(label="可用性", prop="avail")
              el-radio(v-model="formData.avail", label="1", :disabled="!isEdit") 启用
              el-radio(v-model="formData.avail", label="0", :disabled="!isEdit") 禁用
          div
            el-form-item(label="版本", prop="version")
              el-select(v-model="formData.version", disabled, style="width: 120px; margin-right: 10px;")
                el-option(v-for="(item, index) in versionSelect", :key="index", :label="item.name", :value="item.value")
              el-button(type="primary", plain, v-if="isEdit", @click="showVersionPop") 版本管理
          div
            el-form-item(label="版本有效期")
              p.height32
                el-input(v-model="formData.versionStart", style="width: 100px;", disabled)
                span(style="padding: 0 10px;") -
                el-input(v-model="formData.versionEnd", style="width: 100px;", disabled)
    .table-title
      span 课程列表（共{{formData.courseArray ? formData.courseArray.length : 0}}门课程）
      el-button.right-btn(type="primary", size="mini", v-if="isEdit", @click="addCourse") 添加课程
    el-table.tcs-pop-table(:data="formData.courseArray", border, size="mini", height="300px")
      el-table-column(show-overflow-tooltip, type="index", label="序号")
      el-table-column(show-overflow-tooltip, prop="courseCode", label="课程编号")
      el-table-column(show-overflow-tooltip, prop="courseName", label="课程名称")
      el-table-column(show-overflow-tooltip, prop="courseVersion", label="版本")
      el-table-column(show-overflow-tooltip, label="培训机构")
        template(slot-scope="scope")
          div {{scope.row.agency | compare-list(agencySelect)}}
      el-table-column(show-overflow-tooltip, label="授课方式")
        template(slot-scope="scope")
          div {{scope.row.form | compare-list(formSelect)}}
      el-table-column(show-overflow-tooltip, label="状态")
        template(slot-scope="scope")
          div {{scope.row.status | compare-list(statusSelect)}}
      el-table-column(show-overflow-tooltip, label="可用性")
        template(slot-scope="scope")
          div {{scope.row.avail | compare-list(availSelect)}}
      el-table-column(label="操作", min-width="60px", fixed="right", v-if="isEdit")
        template(slot-scope="scope")
          i.icon-act.el-icon-delete(@click="deleteCourse(scope.$index, scope.row)")
    .dialog-footer(slot="footer")
      el-button(type="primary", plain, @click="closeDialog") 取消
      el-button(type="primary", @click="saveCourseSet", v-if="isEdit", :disabled="saving") 保存
      el-button(type="primary", @click="submitCourseSet", v-if="isEdit", :disabled="submitting") 保存并发布
  //- 版本管理
  version-popup(
    :visible.sync="vpVisible",
    :parent-data="vpData",
    @submit="onVpSubmit",
    @close="vpVisible = false")
  //- 选择课程
  course-list(
    :visible.sync="clVisible",
    @submit="onClSubmit",
    @close="clVisible = false")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import CheckoutApi from '@/api/inventory/inbound';
import VersionPopup from '@/components/manage/train/versionPopup';
import CourseList from '@/components/manage/train/courseList';

// 使内容为空时不提示
const validValue = (rule, value, callback) => {
  callback();
};

export default {
  name: 'coursesetpopup',
  components: {
    VersionPopup,
    CourseList
  },
  props: {
    title: String,
    visible: Boolean,
    isEdit: Boolean,
    parentData: Object
  },
  data() {
    return {
      // 新建时初始数据
      formData: this.parentData,
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编码', trigger: 'blur', validator: validValue }
        ],
        desc: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        avail: [
          { required: true, message: '请选择可用性', trigger: 'change' }
        ]
      },
      // 版本管理
      vpVisible: false,
      vpData: {},
      // 课程popup
      clVisible: false,
      // 避免重复提交
      saving: false,
      submitting: false,
      // 下拉框选项
      versionSelect: [],
      statusSelect: [
        { name: '保存', value: 0 },
        { name: '待发布', value: 1 },
        { name: '已发布', value: 2 },
        { name: '已终止', value: 3 },
        { name: '已完成', value: 4 }
      ],
      availSelect: [
        { name: '启用', value: 0 },
        { name: '禁用', value: 1 }
      ]
    };
  },
  computed: {
    ...mapGetters({
      agencySelect: 'agencySelect',
      formSelect: 'crsFormSelect'
    })
  },
  watch: {
    parentData(newData, oldData) {
      if (newData !== oldData) {
        this.formData = newData;
        // 避免初始显示表单校验结果
        setTimeout(() => {
          this.clearValidate();
        }, 10);
      }
    }
  },
  created() {
    // 员工列表
    ComApi.getEmployees().then((personList) => {
      this.createUserSelect = personList;
    });
  },
  methods: {
    // 版本管理
    showVersionPop() {
      this.vpVisible = true;
      this.vpData = { versionList: [] };
    },
    // 保存版本管理
    onVpSubmit(data) {
      console.log(data);
    },
    /* ****** 表格操作  ****** */
    // 添加
    addCourse() {
      this.clVisible = true;
    },
    // 课程
    onClSubmit(data) {
      if (data) {
        if (!this.formData.courseArray) {
          this.$set(this.formData, 'courseArray', []);
        }
        for (const value of data) {
          this.formData.courseArray.push(value);
        }
      }
    },
    // 删除
    deleteCourse(index) {
      this.formData.courseArray.splice(index, 1);
    },
    // 移除表单的校验结果
    clearValidate() {
      if (this.$refs.formData) {
        this.$refs.formData.clearValidate();
      }
    },
    // 关闭、取消
    closeDialog() {
      this.clearValidate();
      this.$emit('close');
    },
    // 保存
    saveCourseSet() {
      if (this.saving) {
        return false;
      }
      this.saving = true;
      this.$refs.formData.validate((valid) => {
        if (!valid) {
          this.$message.error('必填项不能为空');
          this.saving = false;
          return false;
        }
        const params = { ...this.formData };
        CheckoutApi.saveNewInvCheckout(params).then((res) => {
          if (!res.status) {
            if (!this.formData.code) {
              // 新增
              res.obj.isNew = true;
            } else {
              res.obj.isNew = false;
            }
            this.$emit('submit', res.obj);
            this.closeDialog();
            this.$message({ message: '保存成功', type: 'success' });
            this.saving = false;
          } else {
            this.$message.error(res.comment || '保存失败');
            this.saving = false;
          }
        }).catch((error) => {
          this.saving = false;
          console.log(JSON.stringify(error));
          this.$message.error('网络不给力，请稍后再试');
        });
        return true;
      });
    },
    // 盘点单提交
    submitCourseSet() {
      if (this.submitting) {
        return false;
      }
      this.submitting = true;
      this.$refs.formData.validate((valid) => {
        if (!valid) {
          this.$message.error('必填项不能为空');
          this.submitting = false;
          return false;
        }
        const params = { ...this.formData };
        CheckoutApi.submitNewInvCheckout(params).then((res) => {
          if (!res.status) {
            if (!this.formData.code) {
              // 新增
              res.obj.isNew = true;
            } else {
              res.obj.isNew = false;
            }
            this.$emit('submit', res.obj);
            this.closeDialog();
            this.$message({ message: '提交成功', type: 'success' });
            this.submitting = false;
          } else {
            this.$message.error(res.comment || '提交失败');
            this.submitting = false;
          }
        }).catch((error) => {
          this.submitting = false;
          console.log(JSON.stringify(error));
          this.$message.error('网络不给力，请稍后再试');
        });
        return true;
      });
    }
  }
};
</script>

<style lang="sass">
$SEARCHHEIGHT: 104px
$SELECTWIDTH: 100px
.cp-train-cs-popup
  .el-table
    th, td
      text-align: center
  .tcs-pop
    &::-webkit-scrollbar
      display: none
    .el-dialog
      margin-top: 5vh!important
    .el-dialog__footer
      text-align: center
      padding-top: 0
      .el-button
        min-width: 80px
  .tcs-pop-form
    .el-col
      overflow: inherit
    .el-form-item
      width: 100%
      height: 34px
      margin-right: 0
    .el-form-item__label
      width: 80px
      text-align: left
    .el-form-item__content
      min-width: 120px
      width: calc(100% - 80px)
    .el-select, .el-date-editor.el-input
      width: 100%
    .input-time
      .el-input--prefix .el-input__inner
        padding-left: 26px
        padding-right: 0
    .height32
      height: 32px
      line-height: 32px
  .table-title
    overflow: hidden
    line-height: 28px
    margin: 10px 0
    .right-btn
      display: inline-block
      float: right
  .tcs-pop-table
    .icon-act
      font-size: 16px
      font-weight: 500
      padding: 4px
      cursor: pointer
      &:hover
        color: #5D9BFB
</style>
